import { Plugin } from 'siyuan'
import { setupEventListeners } from './docUtils'
import { MenuManager } from './menuManager'
import { EventHandlers } from './eventHandlers'
import { createApp } from 'vue'
import ChatPanel from '@/views/ChatPanel.vue'

/**
 * 插件管理器
 * 负责插件的初始化和管理
 */
export class PluginManager {
  private plugin: Plugin
  private eventHandlers: EventHandlers
  private removeEventListeners: (() => void) | null = null
  private chatApp: any = null

  constructor(plugin: Plugin, eventHandlers: EventHandlers) {
    this.plugin = plugin
    this.eventHandlers = eventHandlers
  }

  /**
   * 初始化插件
   */
  init() {
    this.setupTopBar()
    this.setupDock()
    this.setupEventListeners()
  }

  /**
   * 设置顶栏按钮
   */
  private setupTopBar() {
    this.plugin.addTopBar({
      icon: 'iconEmoji',
      title: 'CH工具箱',
      callback: (event: MouseEvent) => {
        MenuManager.showMainMenu(event, {
          onShowForm: this.eventHandlers.showTestForm,
          onLoadDoc: this.eventHandlers.loadCurrentDoc,
          onOptimizeTitle: this.eventHandlers.optimizeTitle,
          onOpenSidebar: this.eventHandlers.openSidebar,
          onShowHelp: this.eventHandlers.showHelp,
          onShowAbout: this.eventHandlers.showAbout
        })
      }
    })
  }

  /**
   * 设置侧边栏面板
   */
  private setupDock() {
    const dockType = "ai-chat-panel"
    this.plugin.addDock({
      config: {
        position: "RightTop",
        size: { width: 500, height: 400 },
        icon: "iconDock",
        title: "AI对话面板"
      },
      data: {},
      type: dockType,
      init: (dock) => {
        // 清空dock元素内容
        dock.element.innerHTML = ''
        dock.element.style.height = '100%'
        dock.element.style.overflow = 'hidden'
        
        // 创建Vue应用实例
        this.chatApp = createApp(ChatPanel)
        this.chatApp.mount(dock.element)
      },
      destroy: () => {
        // 清理Vue应用实例
        if (this.chatApp) {
          this.chatApp.unmount()
          this.chatApp = null
        }
      }
    })
    
    // 监听打开侧边栏事件
    window.addEventListener('openSidebar', () => {
      // 查找并点击侧边栏图标
      const dockIcon = document.querySelector(`[data-type="${dockType}"]`) as HTMLElement
      if (dockIcon) {
        dockIcon.click()
      } else {
        // 备用方案：查找包含我们插件标题的dock图标
        const allDockIcons = document.querySelectorAll('.dock__item')
        for (const icon of allDockIcons) {
          if (icon.getAttribute('aria-label')?.includes('AI对话面板')) {
            (icon as HTMLElement).click()
            break
          }
        }
      }
    })
    
    // 监听关闭dock事件
    window.addEventListener('closeDock', () => {
      // 查找并点击侧边栏图标来关闭面板（再次点击会切换状态）
      const dockIcon = document.querySelector(`[data-type="${dockType}"]`) as HTMLElement
      if (dockIcon) {
        dockIcon.click()
      } else {
        // 备用方案：查找包含我们插件标题的dock图标
        const allDockIcons = document.querySelectorAll('.dock__item')
        for (const icon of allDockIcons) {
          if (icon.getAttribute('aria-label')?.includes('AI对话面板')) {
            (icon as HTMLElement).click()
            break
          }
        }
      }
    })
  }

  /**
   * 设置事件监听器
   */
  private setupEventListeners() {
    this.removeEventListeners = setupEventListeners({
      onBlockIconClick: this.eventHandlers.onBlockIconClick
    })
    console.log('事件监听器设置完成')
  }

  /**
   * 清理资源
   */
  cleanup() {
    if (this.removeEventListeners) {
      this.removeEventListeners()
      this.removeEventListeners = null
    }
    
    // 清理Vue应用实例
    if (this.chatApp) {
      this.chatApp.unmount()
      this.chatApp = null
    }
  }
}